package com.cloud.wyf.Service.imp;

import com.cloud.wyf.Entity.User;
import com.cloud.wyf.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Service
public class LoginServiceImp implements UserDetailsService {

    @Autowired
    UserService us;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null) throw new UsernameNotFoundException("用户名不能为空");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //String inputCode=(String)request.getAttribute("code");
       // String code = (String) request.getSession().getAttribute("index_code");

        User user = us.selectByName(username);

        if (user == null) throw new UsernameNotFoundException("用户名不存在");
        request.getSession().setAttribute("user",user);
        if(user.getRole()==0)
        return org.springframework.security.core.userdetails.User.withUsername(user.getNickname())
                .password(user.getPassword())
                .roles("admin").build();
     if(user.getRole()==1)
            return org.springframework.security.core.userdetails.User.withUsername(user.getNickname())
                    .password(user.getPassword())
                    .roles("leader").build();
    else if(user.getRole()==2) return org.springframework.security.core.userdetails.User.withUsername(user.getNickname())
                    .password(user.getPassword())
                    .roles("middel").build();
     else return org.springframework.security.core.userdetails.User.withUsername(user.getNickname())
             .password(user.getPassword())
             .roles("ordinary").build();

    }


}
